package com.jrx.anytxn.param.controller.limit;

import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.config.AdjustLimitFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.service.limit.IAdjustListService;
import com.jrx.anytxn.param.utils.ReadCsvUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @Classname AdjustLimitController
 * @Description 批量调额
 * @author  by lbz
 */
@Api(tags = "批量调额")
@RestController
@RequestMapping("/param/adjustLimit")
public class AdjustLimitController {

    private static final Logger logger= LoggerFactory.getLogger(AdjustLimitController.class);

    @Autowired
    private AdjustLimitFileConfig adjustLimitFileConfig;
    @Autowired
    private IAdjustListService adjustListService;


    @ApiOperation(value = "批量调额", notes = "批量调额")
    @PostMapping(value = "/upload")
    public TxnRespResult<Boolean> upload(@RequestParam("file") MultipartFile upfile,@RequestParam String tenantId,
                                         @RequestParam String userName) throws Exception {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        logger.info("批量调额开始:startTime:{}",result.getStartTime());

        Boolean flag;
        String organizationId = Constant.DEFAULT_ORG_NUMBER;
        try{
            byte[] bate =upfile.getBytes();
            //检查文件
            List<Map<String,Object>> fileList = ReadCsvUtil.getResource(bate);
            String path = adjustLimitFileConfig.getBasePath() + "/" + tenantId + "/";
            adjustListService.transferAdjustFile(upfile,organizationId,tenantId,userName,path,fileList.size());
            flag = true;
            result.getSuccess(flag);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            adjustListService.buildAdjustFileLog(upfile,organizationId,tenantId,userName);
            result.getFail(9999, "文件读取失败");
        }
        logger.debug("批量调额结束endTime{}",result.getEndTime());
        return result;
    }

    @ApiOperation(value = "下载调额模板", notes = "下载调额模板")
    @GetMapping(value = "/downLoad")
    public void downLoad(HttpServletResponse response, @RequestParam("filePath") String filePath,@RequestParam String tenantId) {
        String templatePath = adjustLimitFileConfig.getBasePath() + "/" + tenantId + "/";
        logger.info("下载调额模板地址：{}", templatePath);
        response.setContentType("application/csv");
        File file = new File(templatePath + filePath);
        try (FileInputStream fileInputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream();) {
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
            response.setHeader("Content-Disposition", "inline; filename= adjustLimitTemplate.csv");
            outputStream.flush();
        } catch (Exception e) {
            logger.error("下载调额模板异常", e);
        }
    }
}
